<template>
  <div>
    <el-upload
        ref="upload"
        :on-error="error"
        action="#"
        accept=".png,.jpg"
        :headers="headers"
        :on-success="success"
        :file-list="file"
        list-type="picture-card"
        :auto-upload="true"
        :show-file-list="false"
        :http-request="commitPic"
        :before-upload="beforeAvatarUpload">
      <img v-if="''!==file && file[0].url" :src="file[0].url" class="avatar" style="width: 148px;height: 148px">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" :append-to-body="true">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>


</template>

<script>

export default {
  data() {
    return {
      headers: {'Authorization':sessionStorage.getItem('token')},
      file:[],
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false
    };
  },
  props:{
    files:''
  },
  watch:{
    files:{
      immediate:true,
      handler(){
        try{
          this.file=JSON.parse(JSON.stringify(this.files))
        }catch (e) {

        }

      }
    },
  },
  methods: {
    commitPic(file){
      console.log(888)
      console.log(file)
      const formData = new FormData();
      formData.append("file", file.file);
      this.$api.myUploadSingle(formData).then(res=>{
        if(res.data){
          this.$message.success("上传成功")
          this.file=[res.data]
          this.$emit('set',res.data.url)
        }else{
          this.$message.error("上传失败")
        }
      }).catch(err=>{
        this.$message.error(err.message)
      })
    },
    beforeAvatarUpload(file) {
      //const isJPG = file.type === 'image/jpeg';
      //const isLt2M = file.size / 1024 / 1024 < 2;

      // if (!isJPG) {
      //   this.$message.error('上传图片只能是图片格式!');
      // }
      // return isJPG
     /* if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }*/
      //return isJPG //&& isLt2M;
    },
    error(e){
      console.log(e)
    },
    success(res){
      console.log(res)
      this.file=[res.data]
    },
    handleRemove(file) {
      console.log(file);
      this.$refs.upload.clearFiles();
      this.file=[]
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;

      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    }
  }
}
</script>

<style lang="less" scoped>
.ivu-upload{
  width: 320px;
}
</style>

